package com.bolt.admin.module.sys.service;

import com.bolt.admin.module.sys.entity.AreaEntity;
import com.bolt.admin.module.sys.repository.AreaRepository;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.base.service.BaseService;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import com.bolt.support.ui.tree.model.TreeDataProvider;
import com.bolt.support.ui.tree.vo.UITreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Auto Generate Javadoc
 *
 * @author 日期:2018-02-07 16:11:28
 *         中国行政地区表
 **/
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class AreaService extends BaseService <AreaEntity, Long> implements TreeDataProvider <Long> {
    @Autowired
    private AreaRepository areaRepository;

    @Override
    protected BasicJpaRepository <AreaEntity, Long> getRepository() {
        return areaRepository;
    }

    public List <AreaEntity> findAllCached() {
        return areaRepository.findAllCached();
    }

    public List <AreaEntity> findRoots() {
        return areaRepository.findRoot();
    }

    /**
     * 根据父ID查询此级的下级节点
     *
     * @param id
     * @return
     */
    public List <AreaEntity> findChildren(Long id) {
        return areaRepository.findByPid(id);
    }

    public AreaEntity findByAreaCode(String code) {
        return areaRepository.findByAreaCode(code);
    }

    /**
     * @param parentId
     * @param params
     * @return
     */
    @Override
    public List <UITreeNode> getChildren(Long parentId, Map <String, String> params) {
        List <UITreeNode> children;
        try {
            children = new ArrayList <>();
            List <AreaEntity> areaList;
            if (parentId == null) {
                areaList = findRoots();
            } else {
                areaList = findChildren((Long) parentId);
            }
            for (AreaEntity area : areaList) {
                UITreeNode treeNode = new UITreeNode();
                treeNode.setName(area.getName());
                treeNode.setId(String.valueOf(area.getId()));
                treeNode.setParent(area.getLevel() < 2);
                treeNode.putAttribute("areaCode", area.getAreaCode());
                treeNode.putAttribute("areaLevel", String.valueOf(area.getLevel()));
                children.add(treeNode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            throw new ServiceException(ex);

        }
        return children;
    }
}
